<template>
  <div class="page-container">
    <div class="in-container">
      <ApplicationAddSearchFrom
        @saveData="saveData"
        :tableData="tableData.data"
        ref="applicationAddSearchFromRef"
        @clearTableData="clearTableData"
        @editRefresh="editRefresh"
      ></ApplicationAddSearchFrom>
      <div class="btn-box" >
        <el-button v-if="checkStatus != 1 && checkStatus != 2" type="primary" @click="openPayableFee">请款费用</el-button>
        <el-button v-if="checkStatus != 1 && checkStatus != 2" type="primary" @click="deleWriteOff"> 删除请款</el-button>
      </div>
      <AppPageTable
        stripe
        :data="tableData.data"
        :autostyle="'height: calc(100% - 304px);'"
        :isPagination="true"
        :option="tableData.option"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          width="60"
          label="序号"
          type="index"
          fixed="left"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="doccode"
          width="115"
          label="业务编号"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="blNo" width="115" label="提单号" align="center">
        </el-table-column>
        <el-table-column prop="feeName" align="center" label="费用类型">
        </el-table-column>
        <el-table-column
          prop="currency"
          align="center"
          label="币种"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="totalmoney"
          align="center"
          label="金额"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="createBy"
          align="center"
          label="请款人"
          width="115"
        >
        </el-table-column>
        <el-table-column prop="invoiceCode" align="center" label="发票号">
          <template #default="scope">
            {{ scope.row.invoiceCode }}
          </template>
        </el-table-column>
        <el-table-column
          prop="invoiceDate"
          align="center"
          label="发票日期"
          width="140"
        >
          <template #default="scope">
            {{ scope.row.invoiceDate?.split(' ')[0] }}
            
          </template>
        </el-table-column>
        <el-table-column prop="feeMemo" align="center" label="备注">
        </el-table-column>
      </AppPageTable>
    </div>
    <ApplicationAddFee
      ref="applicationAddFeeRef"
      @applicationSelectOver="selectOver"
    ></ApplicationAddFee>
  </div>
</template>
  
  <script>
import { defineComponent } from "vue";
import ApplicationAddSearchFrom from "./ApplicationAddSearchFrom.vue";
import ApplicationAddFee from "./ApplicationAddFee.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatNum } from "@/utils/format.ts";
import { validateNumber } from "@/utils/validate.js";
import bus from "@/utils/vueBus";
export default defineComponent({
  components: {
    AppPageTable,
    ApplicationAddSearchFrom,
    ApplicationAddFee,
  },
  props: {
    doctype: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      checkStatus: 0,
      //表格数据
      tableData: {
        data: [],
        option: useTableOption(),
      },
      // 合计金额
      totalCount: {
        // 应付合计
        sumtotalmoney: 0,
        // 已销金额
        sumverificationMoney: 0,
        // 未销金额
        unVerificationMoney: 0,
      },
      colIndex: -1,
      rowIndex: -1,
      exchangeRateData: [],
    };
  },
  methods: {
    validateNumber,

    // 打开请款费用弹窗
    openPayableFee() {
      const sonVal = this.$refs.applicationAddSearchFromRef.query;
      // 查询条件需要先输入请款币种和结算对象
      if (!sonVal.entId || !sonVal.currency) {
        this.$message.warning("请输入结算对象名称和请款币种");
        return;
      }
      this.$refs.applicationAddFeeRef.open(
        sonVal.currency,
        sonVal.entId,
        sonVal.sumtotalmoney,
        0
      );
    },
    // 删除销账
    async deleWriteOff() {
      if (!this.tableData.option.selected.length) {
        this.$message.warning("请选择数据");
        return;
      }
      ElMessageBox.confirm("是否确定执行删除操作？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let newArray = [];
        this.tableData.data.forEach((t) => {
          if (!this.tableData.option.selected.find((item) => t == item)) {
            newArray.push(t);
          }
        });
        this.tableData.data = newArray;
        this.refreshCount([]);
      });
    },
    // 选中的表格数据
    selectOver(selectTableData) {
      let CpoySelectTableData = JSON.parse(JSON.stringify(selectTableData));
      CpoySelectTableData.forEach(item => {
        item.invoiceCode = item.invoice?.invoiceCode;
        item.invoiceDate = item.invoice?.invoiceDate;
      })
      this.refreshCount(CpoySelectTableData);
    },

    // 重置表格数据
    clearTableData() {
      this.tableData.data = [];
      this.tableData.option.selected = [];
    },

    refreshCount(selectTableData) {
      this.totalCount = {
        // 应付合计
        sumtotalmoney: 0,
        // 已销金额
        sumverificationMoney: 0,
        // 未销金额
        unVerificationMoney: 0,
      };
      this.tableData.data = this.mergeAndRemoveDuplicates(
        JSON.parse(JSON.stringify(selectTableData)),
        JSON.parse(JSON.stringify(this.tableData.data))
      );
      let totalMoneySum = 0;
      for (const iterator of this.tableData.data) {
        totalMoneySum += iterator.totalmoney ? iterator.totalmoney : 0;
      }
      if (this.tableData.data.length) {
        this.$refs.applicationAddSearchFromRef.query.createBy =
          this.tableData.data[0].createBy;
        this.$refs.applicationAddSearchFromRef.query.createTime =
          dayjs().format("YYYY-MM-DD HH:mm:ss");
      }
      this.$refs.applicationAddSearchFromRef.query.totalmoney = totalMoneySum;
    },

    // 合并数组并去重
    mergeAndRemoveDuplicates(arr1, arr2) {
      let hash = {};
      // 合并两个数组
      let newArr = arr1.concat(arr2);
      const mergedArr = newArr.reduce((item, next) => {
        hash[next.workfeeId]
          ? ""
          : (hash[next.workfeeId] = true && item.push(next));
        return item;
      }, []);
      return mergedArr;
    },

    // 选择的费用数据重新组合 data = this.tableData
    resetFeeList(data) {
      let feeList = [];
      for (const iterator of data) {
        let obj = {};
        obj = {
          docId: iterator.docId,
          workfeeId: iterator.workfeeId,
          verificationMoney: iterator.verificationMoney,
          feeMemo: iterator.feeMemo,
          isDeleted: iterator.isDeleted,
          isIncome: iterator.isIncome,
          doccode: iterator.doccode,
          blNo: iterator.blNo,
          feeName: iterator.feeName,
          currency: iterator.currency,
          totalmoney: iterator.totalmoney,
          invoiceCode: iterator.invoiceCode,
          invoiceDate: iterator.invoiceDate,
          balanceDoccode: iterator.balanceDoccode,
          getUnVerificationMoney: iterator.getUnVerificationMoney,
          getTotalmoney: iterator.getTotalmoney,
          getVerificationMoney: iterator.getVerificationMoney,
        };
        if (iterator.id) {
          obj["id"] = iterator.id;
        }
        feeList.push(obj);
      }
      return feeList;
    },

    // 当前页面应收应付下的币种汇率
    async getExchangeRateData() {
      let res = await this.$http.get("/api/base/exchangerate/query", {
        IsIncome: this.query.doctype,
      });
      res.content.map((item) => {
        this.exchangeRateData[item.currency + item.isIncome] =
          item.exchangeRate;
      });
      // 应收或应付对账页面跳转
      if (this.$route.query.currency) {
        this.query.currency = this.$route.query.currency;
        this.query.feeCurrency = this.$route.query.currency;
        this.query.exchangeRate =
          this.exchangeRateData[this.query.feeCurrency + this.query.doctype];
        let selectedIds = JSON.parse(this.$route.query.selectedIds)
          ? JSON.parse(this.$route.query.selectedIds)
          : [];
        if (selectedIds instanceof String) {
          selectedIds = [selectedIds];
        }
        this.$http
          .post(`/api/docBalance/getFeeListByBalanceIds?feeStatus=0`, {
            idArray: selectedIds,
          })
          .then((res) => {
            const tmp = res[0];
            this.query.entCode = tmp.entCode;
            this.query.entFullname = tmp.entFullname;
            this.query.entId = tmp.entId;
            // this.$refs.applicationAddSearchFromRef.getBusDetail(tmp.entCode);  //根据endtCode查询无法获取到对应的数据
            this.$refs.applicationAddSearchFromRef.getCurrentData(
              this.$route.query.currency
            );
            this.$refs.applicationAddSearchFromRef.settlementList = [
              {
                label: this.query.entCode,
                value: this.query.entId,
              },
            ];
            const rows = res.filter(
              (item) => item.currency == this.$route.query.currency
            );
            if (rows.length > 0) {
              let CpoySelectTableData = JSON.parse(JSON.stringify(rows));
              this.tableData.data = CpoySelectTableData;
              CpoySelectTableData.forEach((item) => {
                item.getVerificationMoney = item.getUnVerificationMoney;
                item.verificationMoney = item.getUnVerificationMoney;
                item.x_verificationMoney = item.verificationMoney;
                item.xverificationMoney = Math.trunc(
                  item.totalmoney - item.getUnVerificationMoney
                );
                item.getUnVerificationMoney = Math.trunc(
                  item.totalmoney -
                    item.verificationMoney -
                    item.xverificationMoney
                );
                item.x_unVerificationMoney = item.getUnVerificationMoney;
              });
              //this.refreshCount(CpoySelectTableData, "searchChange", "settingSumtotalmoney");
            }
          });
      }
    },
    // 保存==
    async saveData(query) {
      query.totalmoney = query.totalmoney ? parseFloat(query.totalmoney) : 0;
      let reqData = {
        reqCashItems: this.resetFeeList(this.tableData.data),
        ...query,
        id: this.$route.query.id ? this.$route.query.id : 0,
      };
      if (query.isDZ) {
        reqData.docCashItemList.forEach((item) => {
          item.workfeeId = item.id;
        });
      }
      let res = await this.$http.post("/api/docreqcash/save", reqData);
      if (res.status) {
        this.$router.push("/finance/ApplicationFunds");
      } else {
        ElMessage.warning(res.message);
      }
    },
    //编辑数据刷新
    editRefresh() {
      this.getDetailsData();
    },
    //搜索内容数据填充
    fillDataByRouter(searchData) {
      let fromQuery = this.$refs.applicationAddSearchFromRef.query;
      for (const iterator of Object.keys(fromQuery)) {
        fromQuery[iterator] = searchData[iterator];
      }
      for (const iterator of searchData.docReqCashItemResDtos) {
        iterator.id = iterator.workfeeId;
        iterator.invoiceDate = iterator.invoiceDate
          ? dayjs(iterator.invoiceDate).format("YYYY-MM-DD")
          : "";
        iterator.createtime = iterator.createtime
          ? dayjs(iterator.createtime).format("YYYY-MM-DD HH:mm:ss")
          : "";
      }
      this.tableData.data = searchData.docReqCashItemResDtos;
      this.refreshCount(JSON.parse(JSON.stringify(this.tableData.data)));
    },
    //从请款页面跳转填充数据
    async getDetailsData() {
      let queryId = this.$route.query.id;
      if (queryId) {
        let searchData = await this.$http.get("/api/docreqcash/get", {
          id: queryId,
        });
        if (!searchData.status) {
          this.$message.warning(searchData.message);
          return;
        }
        this.checkStatus = searchData.data.checkStatus;
        this.$store.dispatch("tab/modifyTabTitle", {
          path: this.$route.fullPath,
          title: this.$route.query.title,
        });
        this.fillDataByRouter(searchData.data);
        this.$refs.applicationAddSearchFromRef.getBankAccount(
          searchData.data.currency
        );
      }
    },
  },
  watch: {},

  mounted() {
    this.getDetailsData();
  },
});
</script>
  
  <style lang="scss" scoped>
.btn-box {
  margin-bottom: 8px;
}
</style>
  